package info.liujiachen.security.test.config;

import info.liujiachen.security.test.pojo.JwtUserDetails;
import info.liujiachen.security.test.service.JwtUserDetailsService;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class JwtAuthenticationProvider implements AuthenticationProvider {

    private JwtUserDetailsService detailsService;

    public JwtAuthenticationProvider(JwtUserDetailsService detailsService) {
        this.detailsService = detailsService;
    }

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        JwtAuthenticationToken result = null;
        if (supports(auth.getClass())) {
            String username = (String) auth.getPrincipal();
            JwtUserDetails details = detailsService.getCacheUser(username);
            if (details == null) {
                throw new UsernameNotFoundException("Token User Not Found");
            }
            result = new JwtAuthenticationToken(details.getUsername(), auth.getCredentials(), details.getAuthorities());
            result.setDetails(auth.getDetails());
        }
        return result;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return JwtAuthenticationToken.class.isAssignableFrom(aClass);
    }



}
